package com.graduate.cec.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.graduate.cec.common.JsonPage;
import com.graduate.cec.common.ResponseCode;
import com.graduate.cec.exception.CecServiceException;
import com.graduate.cec.mapper.*;
import com.graduate.cec.pojo.dto.ArticleDTO;
import com.graduate.cec.pojo.dto.ArticleOperateDTO;
import com.graduate.cec.pojo.dto.ArticleSimpleDTO;
import com.graduate.cec.pojo.dto.ArticleSimplePageDTO;
import com.graduate.cec.pojo.entity.*;
import com.graduate.cec.pojo.vo.ArticleDetailVO;
import com.graduate.cec.util.CopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class ArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private NationMapper nationMapper;

    @Resource
    private CollectMapper collectMapper;

    @Resource
    private LoveMapper loveMapper;

    @Resource
    private ArticleDetailMapper articleDetailMapper;

    String dirPath = null;


    /****************        增       ******************************************************************/
    public Long insertArticle(ArticleDTO article){

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String phone = (String) principal;
        Long id = userMapper.selectIdByPhone(phone);
        article.setUserId(id);

        Nation nation = nationMapper.selectByPrimaryKey(article.getNationId());
        article.setNationName(nation.getName());

        Article copy = CopyUtil.copy(article, Article.class);
        int i = articleMapper.insertSelective(copy);

        System.out.println(copy);

        ArticleDetail articleDetail = new ArticleDetail();

        articleDetail.setArticleId(copy.getId());
        articleDetail.setContent(article.getContent());
        int i1 = articleDetailMapper.insertSelective(articleDetail);

        if(i1 != 1){
            throw new CecServiceException(ResponseCode.INSERT_INFO_ERROR,"新增失败!");
        }
        if (i != 1){
            throw new CecServiceException(ResponseCode.INSERT_INFO_ERROR,"新增失败!");
        }

        return copy.getId();

    }

    //上传图片
    public String uploadPictures(MultipartFile picFile) throws Exception {
        String urlStr = URLUtil.getURL(FileUtil.file("picture")).toString();
        dirPath = urlStr.substring(urlStr.indexOf("cec"), urlStr.indexOf("target"));
        String prefix = urlStr.substring(6, urlStr.indexOf("cec"));
        dirPath += "picture/";
        dirPath = prefix + dirPath + "article";

        String fileName = picFile.getOriginalFilename();

        //得到后缀名 从最后一个.出现的位置截取到最后
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名 UUID.randomUUID()得到一个唯一标识符
        fileName = UUID.randomUUID() + suffix;
        log.info("fileName = " + fileName);
        //准备保存图片的文件夹路径
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath + "/" + fileName;
        log.info("filePath = " + filePath);
        //把文件保存到此路径
        picFile.transferTo(new File(filePath));
        //"http://localhost:19090/picture/article/"
        return  "http://localhost:19090/picture/article/" + fileName;
    }




    /****************        删       ******************************************************************/
    //删除上传的图片
    public void removePicture(String pictureName) {
        System.out.println(pictureName);
        String[] split = pictureName.split("/");
        pictureName = split[split.length - 1];
        System.out.println(pictureName);
        String filePath = dirPath + "/" + pictureName;
        System.out.println(filePath);
        new File(filePath).delete();
    }

    public void deleteByKeys( List<Long> id){

        int i = articleMapper.deleteByPrimaryKey(id);
        if (i != 0){
            return ;
        }else{
            throw new CecServiceException(ResponseCode.DELETE_INFO_ERROR,"删除失败!");
        }
    }







    /****************        改       ******************************************************************/
    public void updateByKey(Article article){
        int i = articleMapper.updateByPrimaryKeySelective(article);
        if (i == 1){
            return;
        }else{
            throw new CecServiceException(ResponseCode.UPDATE_INFO_ERROR,"修改失败");
        }
    }

    public void updateOperateByKey(ArticleOperateDTO articleOperateDTO){
        if(articleOperateDTO.getCollectCount() == null){
            Article article = articleMapper.selectByPrimaryKey(articleOperateDTO.getId());
            articleOperateDTO.setCollectCount(article.getCollectCount()-1);
        }
        Article article = new Article();

        article.setId(articleOperateDTO.getId());
        article.setCollectCount(articleOperateDTO.getCollectCount());
        article.setLoveCount(articleOperateDTO.getLoveCount());
        int i = articleMapper.updateByPrimaryKeySelective(article);

        if(articleOperateDTO.getType() == 1){
            Love love = new Love();
            love.setLoveId(articleOperateDTO.getId());
            love.setUserId(articleOperateDTO.getUserId());
            loveMapper.insertSelective(love);
        }else if (articleOperateDTO.getType() == 2){
            LoveExample loveExample = new LoveExample();
            LoveExample.Criteria criteria = loveExample.createCriteria();
            criteria.andUserIdEqualTo(articleOperateDTO.getUserId());
            criteria.andLoveIdEqualTo(articleOperateDTO.getId());
            loveMapper.deleteByExample(loveExample);
        }else if(articleOperateDTO.getType() == 3){
            Collect collect = new Collect();
            collect.setArticleId(articleOperateDTO.getId());
            collect.setUserId(articleOperateDTO.getUserId());
            collectMapper.insertSelective(collect);
        }else{
            CollectExample collectExample = new CollectExample();
            CollectExample.Criteria criteria = collectExample.createCriteria();
            criteria.andUserIdEqualTo(articleOperateDTO.getUserId());
            criteria.andArticleIdEqualTo(articleOperateDTO.getId());
            collectMapper.deleteByExample(collectExample);
        }

        if (i == 1){
            return;
        }else{
            throw new CecServiceException(ResponseCode.UPDATE_INFO_ERROR,"修改失败");
        }
    }



    /****************        查       ******************************************************************/
    public List<Article> getListByNationId(Long nationId){
        List<Article> articles = articleMapper.selectByNationId(nationId);
        return articles;
    }

    public List<Article> selectByNation(Long id){
        List<Article> articles = articleMapper.selectByNation(id);
        return articles;
    }



    public ArticleDetailVO getArticleDetail(Long id){
        Article article = articleMapper.selectByPrimaryKey(id);
        ArticleDetailVO articleDetailVO = CopyUtil.copy(article, ArticleDetailVO.class);

        ArticleDetailExample articleDetailExample = new ArticleDetailExample();
        ArticleDetailExample.Criteria criteria = articleDetailExample.createCriteria();
        criteria.andArticleIdEqualTo(id);
        List<ArticleDetail> articleDetails = articleDetailMapper.selectByExampleWithBLOBs(articleDetailExample);

        if(articleDetails.get(0) != null){
            articleDetailVO.setContent(articleDetails.get(0).getContent());
        }

        return articleDetailVO;
    }

    public List<Article> getAllList(Long categoryId){
        List<Article> articles = articleMapper.selectAllList(categoryId);
        return articles;
    }


    public JsonPage<Article> getAllListByUser(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> allListByUser = articleMapper.getAllListByUser(userId);
        return JsonPage.restPage(new PageInfo<>(allListByUser));

    }

    public JsonPage<Article> getAllListByUserAndCollect(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> allListByUser = articleMapper.getAllListByUserAndCollect(userId);
        return JsonPage.restPage(new PageInfo<>(allListByUser));

    }

    public JsonPage<ArticleDetailVO> getAllListManagement(ArticleSimplePageDTO articleSimplePageDTO) {
        PageHelper.startPage(articleSimplePageDTO.getPageNum(), articleSimplePageDTO.getPageSize());

        List<ArticleDetailVO> allListManagement = articleMapper.getAllListManagement(articleSimplePageDTO);

        return JsonPage.restPage(new PageInfo<>(allListManagement));

    }

}
